package duylinh

import org.springframework.dao.DataIntegrityViolationException

class SanPhamController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
    def burningImageService
    def utilsService

    def index() {
        redirect(action: "list", params: params)
    }

    def list(Integer max) {
        params.max = Math.min(max ?: 10, 100)

        def loaiSanPham
        if (params.loaiSanPhamId)
        {
            loaiSanPham = LoaiSanPham.get( params.loaiSanPhamId )
        }

        def sanphamList
        def sanPhamInstanceTotal

        if ( loaiSanPham )
        {
            sanphamList = SanPham.findAllByLoaiSanPham( loaiSanPham, params )
            sanPhamInstanceTotal = SanPham.countByLoaiSanPham( loaiSanPham )
        }
        else
        {
            sanphamList = SanPham.list(params)
            sanPhamInstanceTotal = SanPham.count()
        }


        [sanPhamInstanceList: sanphamList, sanPhamInstanceTotal: sanPhamInstanceTotal, loaiSanPham:loaiSanPham]
    }


    def createEditProductFlow = {

        start {
            action {
                def sP
                if( params.sanPhamId )
                {
                    sP = SanPham.findById( params.sanPhamId )
                    flow.isNewProduct = false
                }
                else
                {
                    sP = new SanPham()
                    flow.isNewProduct = true
                }
                flow.sanPham = sP
                flow.step = 1
            }
            on("success").to "basicInfo"
        }

        basicInfo {

            on("tiep")
            {
                flow.sanPham.properties = params

                def user = User.get(springSecurityService.principal.id)
                if( user )
                {
                    if ( flow.isNewProduct )
                    {
                        flow.sanPham?.creator = user
                    }
                    else
                    {
                        flow.sanPham?.updater = user
                    }
                }

                if( !flow.sanPham.validate() )
                {
                    return error()
                }
                else
                {
                    println("params.avatarChanged " + params.avatarChanged)
                    // save avatar
                    flow.sanPham.save(flush: true)
                    utilsService.saveSanPhamAvatar( flow.sanPham )
                    flow.sanPham.save(flush: true)
                    flow.isNewProduct = true
                }
            }.to("chonHoacTaoVatLieuMoi")

            on("ketthuc"){
                    flow.sanPham.properties = params

                    def user = User.get(springSecurityService.principal.id)
                    if( user )
                    {
                        if ( flow.isNewProduct )
                        {
                            flow.sanPham?.creator = user
                        }
                        else
                        {
                            flow.sanPham?.updater = user
                        }
                    }

                    if( !flow.sanPham.validate() )
                    {
                        return error()
                    }
                    else
                    {
                        println("params.avatarChanged " + params.avatarChanged)
                        // save avatar
                        flow.sanPham.save(flush: true)
                        utilsService.saveSanPhamAvatar( flow.sanPham )
                        flow.sanPham.save(flush: true)

                        flow.isNewProduct = true
                    }

            }.to("thoatFlow")

            on("huy").to("thoatFlow")
        }



        chonHoacTaoVatLieuMoi {
            action {
                if( VatLieu.count() > 0 ){
                    return chonVatLieu()
                } else {
                    return taoVatLieuMoi()
                }
                flow.step = 2
            }
            on("chonVatLieu").to "chonVatLieu"
            on("taoVatLieuMoi").to "taoVatLieuMoi"
            on("ketthuc").to("thoatFlow")
            on(Exception).to "basicInfo"
        }

        chonVatLieu{

            on("chonVatLieu"){
              flow.sanPham.vatLieu =  VatLieu.get( Long.parseLong(params.vatLieu))
              if( !flow.sanPham.validate() )
              {
                  return error()
              }
              else
              {
                  flow.sanPham.save(flush: true)
              }

            }.to("chonHoacTaoCongNheMoi")

            on("suaVatLieu").to( "taoVatLieuMoi" )
            on("taoVatLieu").to ("taoVatLieuMoi")
            on("ketthuc").to("thoatFlow")
        }

        taoVatLieuMoi{
            on("save"){
              def vl
              if ( params.vatLieu )
              {
                vl = VatLieu.findById( params.vatLieu )
              }
              else
              {
                  vl = new VatLieu( params )
                  def user = User.get(springSecurityService.principal.id)
                  vl.creator = user
              }

              flow.sanPham.vatLieu = vl
              if( !vl.validate() )
              {
                  return error()
              }
              else
              {
                  flow.sanPham.save(flush: true)
              }
            }.to("chonHoacTaoCongNheMoi")
            on("ketthuc").to("thoatFlow")
            on("quayLai").to("basicInfo")
        }


        chonHoacTaoCongNheMoi {
            action {
                if( CongNghe.count() > 0 ){
                    return chonCongNghe()
                } else {
                    return taoCongNghe()
                }
                flow.step = 3
            }
            on("chonCongNghe").to "chonCongNghe"
            on("taoCongNghe").to "taoCongNghe"
            on(Exception).to "basicInfo"
        }


        chonCongNghe {
            on("chonCongNghe"){
                flow.sanPham.congNghe =  CongNghe.get( Long.parseLong(params.congNghe))
                if( !flow.sanPham.validate() )
                {
                    return error()
                }
                else
                {
                    flow.sanPham.save(flush: true)
                }
            }.to("thoatFlow")
            on("suaCongNghe").to("taoCongNghe")
            on("taoCongNghe").to("taoCongNghe")
            on("ketthuc").to("thoatFlow")
        }

        taoCongNghe {
            on("back").to ("chonHoacTaoCongNheMoi")

            on("save"){
                def cn

                if( params.congNghe )
                {
                    cn =  CongNghe.findById( params.congNghe )
                }
                else
                {
                    cn = new CongNghe( params )
                    def user = User.get(springSecurityService.principal.id)
                    cn.creator = user
                }

                flow.sanPham?.congNghe = cn
                if( !cn.validate() )
                {
                    return error()
                }
                else
                {
                    println ("save")
                    // save the object
                    flow.sanPham.save(flush: true)
                    println ("save..")
                }

            }.to("themOrSuaNguyenCongAction")
            on("ketthuc").to("thoatFlow")
        }

        themOrSuaNguyenCongAction {
           action{
               def nc

               if( params.nguyenCongId )
               {
                    nc = NguyenCong.findById( params.nguyenCongId )
                    flow.themNguyenCongMoi = false
               }
               else
               {
                   nc = new NguyenCong( )
                   def user = User.get(springSecurityService.principal.id)
                   nc.creator = user
                   flow.themNguyenCongMoi = true
               }
               flow.nguyenCong = nc
               flow.step = 3
               println("flow.nguyenCong... " + flow.nguyenCong)
           }
           on("success").to("themNguyenCong")
        }

        themNguyenCong{

            on ("save"){
             def nc = flow.nguyenCong
             nc.properties = params

             if( !nc.validate() )
             {
                 return error()
             }
             else
             {
                if ( flow.themNguyenCongMoi )
                {
                    flow.sanPham?.congNghe?.addToNguyenCongs( nc )
                    nc.save(flush: true)
                    flow.sanPham.save(flush: true)
                }
                else
                {
                    nc.save(flush: true)
                }

                println("save flush after...")
             }

            }.to("themOrSuaNguyenCongAction")

            on("suaNguyenCong").to ("themOrSuaNguyenCongAction")
            on("xoaNguyenCong").to ("xoaNguyenCong")
            on("upThuTuNguyenCong").to ("upThuTuNguyenCong")
            on("tiep").to("thoatFlow")
            on("huy").to("thoatFlow")
            on("ketthuc").to("thoatFlow")
        }


        xoaNguyenCong {
            action{
                println("params: " + params)
                if( params.nguyenCongId )
                {
                    def nc = NguyenCong.findById( params.nguyenCongId )
                    if( nc )
                    {
                        flow.sanPham?.congNghe?.removeFromNguyenCongs( nc )
                        nc.delete()
                    }
                }
            }
            on("success").to ("themOrSuaNguyenCongAction")

        }

        upThuTuNguyenCong{
            SanPham sp = new SanPham()
        }

        thoatFlow{
            redirect(action: "list")
        }
    }

    def create() {
        [sanPhamInstance: new SanPham(params)]
    }

    def save() {
        def sanPhamInstance = new SanPham(params)
        if (!sanPhamInstance.save(flush: true)) {
            render(view: "create", model: [sanPhamInstance: sanPhamInstance])
            return
        }

        flash.message = message(code: 'default.created.message', args: [message(code: 'sanPham.label', default: 'SanPham'), sanPhamInstance.id])
        redirect(action: "show", id: sanPhamInstance.id)
    }

    def show(Long id) {
        def sanPhamInstance = SanPham.get(id)
        if (!sanPhamInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'sanPham.label', default: 'SanPham'), id])
            redirect(action: "list")
            return
        }

        [sanPhamInstance: sanPhamInstance]
    }

    def edit(Long id) {
        def sanPhamInstance = SanPham.get(id)
        if (!sanPhamInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'sanPham.label', default: 'SanPham'), id])
            redirect(action: "list")
            return
        }

        [sanPhamInstance: sanPhamInstance]
    }

    def update(Long id, Long version) {
        def sanPhamInstance = SanPham.get(id)
        if (!sanPhamInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'sanPham.label', default: 'SanPham'), id])
            redirect(action: "list")
            return
        }

        if (version != null) {
            if (sanPhamInstance.version > version) {
                sanPhamInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'sanPham.label', default: 'SanPham')] as Object[],
                          "Another user has updated this SanPham while you were editing")
                render(view: "edit", model: [sanPhamInstance: sanPhamInstance])
                return
            }
        }

        sanPhamInstance.properties = params

        if (!sanPhamInstance.save(flush: true)) {
            render(view: "edit", model: [sanPhamInstance: sanPhamInstance])
            return
        }

        flash.message = message(code: 'default.updated.message', args: [message(code: 'sanPham.label', default: 'SanPham'), sanPhamInstance.id])
        redirect(action: "show", id: sanPhamInstance.id)
    }

    def delete(Long id) {
        def sanPhamInstance = SanPham.get(id)
        if (!sanPhamInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'sanPham.label', default: 'SanPham'), id])
            redirect(action: "list")
            return
        }

        try {
            sanPhamInstance.delete(flush: true)
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'sanPham.label', default: 'SanPham'), id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'sanPham.label', default: 'SanPham'), id])
            redirect(action: "show", id: id)
        }
    }
}
